<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度录入</title>
</head>
    <style>
        body{
            display: flex;
            justify-content: center;
            height: 100vh;
            align-items: center;
        }
        #text{
            width: 400px;
        }
    </style>
    
<body>
    <input type="text" id="text" onkeydown='if(event.keyCode==13){btn.click()}'>
    <button>添加</button>

    <div id="add">获取</div>

</body>
</html>

<script>
    var dom = document.getElementById("text")
    var btn = document.querySelector("button")
    var add = document.getElementById("add")
    //剪切板
    var clipBoard = navigator.clipboard;

    //获取
    add.addEventListener("click",function(){
        submit("GET","Reader").then(res=>{
            var data = JSON.parse(res.response).data.replace(new RegExp(",","g"),"\n")
            var newdata = prompt(data)
            if(newdata!==null){
                clipBoard.writeText(data).then(() => {
                    console.log("复制成功")
                })
            }
        })
    })
    
    //写入
    btn.addEventListener("click",function(){
        var data = {
            url:dom.value
        }
        submit("POST","writed",data).then(res=>{
            alert("保存成功")
        }).catch(err=>{
            alert("已存在---保存失败")
        })
    })

    
    //请求接口数据
    function submit(method,url,data){
        return new Promise((resolve,reject)=>{
            // 创建一个新的XMLHttpRequest对象
            var xhr = new XMLHttpRequest();

            // 配置请求类型、URL以及是否异步处理
            xhr.open(method, "http://127.0.0.1:3000/" + url, true);
            
            xhr.setRequestHeader("Content-Type","application/json")

            // 设置请求完成的回调函数
            xhr.onreadystatechange = function () {
                // 请求完成并且响应状态码为200
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        // 请求成功，处理响应数据
                        resolve(xhr)
                    } else {
                        // 请求出错，处理错误情况
                        reject(xhr)
                    }
                }
            };
            if(data){
                xhr.send(JSON.stringify(data));
            }else{
                xhr.send()
            }
        })
    }
</script>